// mock/roleUser.ts

// 模拟延迟
const waitTime = (time: number = 100) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(true);
        }, time);
    });
};

// 生成模拟角色数据 (复用 RoleList 的 mock)
const generateMockRoleData = (): any[] => {
    const data = [];

    for (let i = 1; i <= 50; i++) {
        data.push({
            id: `role_${i}`,
            roleName: `角色${i}`,
            roleCode: `ROLE_${i.toString().padStart(3, '0')}`,
            description: `这是角色 ${i} 的描述`,
            createTime: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toISOString(),
            updateTime: new Date(Date.now() - Math.floor(Math.random() * 5000000000)).toISOString(),
            // ... 其他可能的字段
        });
    }

    return data;
};

// 生成模拟用户数据 (复用 UserList 的 mock)
const generateMockUserData = (): any[] => {
    const departments = ['研发部', '销售部', '市场部', '人事部', '财务部'];
    const posts = ['工程师', '设计师', '产品经理', '销售经理', '分析师', '专员'];

    const data = [];

    for (let i = 1; i <= 100; i++) {
        const dept = departments[Math.floor(Math.random() * departments.length)];
        const post = posts[Math.floor(Math.random() * posts.length)];
        const status = i % 3 === 0 ? 2 : 1; // 每第三个用户冻结

        data.push({
            id: i,
            account: `user${i.toString().padStart(3, '0')}`,
            realname: `用户${i.toString().padStart(3, '0')}`,
            sex: i % 2 === 0 ? 1 : 2, // 1: 男, 2: 女
            sex_dictText: i % 2 === 0 ? '男' : '女',
            phone: `138${String(i).padStart(8, '0')}`,
            email: `user${i}@example.com`,
            status: status,
            status_dictText: status === 1 ? '正常' : '冻结',
            avatar: `https://xsgames.co/randomusers/avatar.php?g=pixel&key=${i}`,
            activitiSync: '0',
            createTime: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toISOString(),
            updateTime: new Date(Date.now() - Math.floor(Math.random() * 5000000000)).toISOString(),
            description: `这是用户 ${i} 的描述`,
            workNo: `W${String(i).padStart(5, '0')}`,
            post: post,
            telephone: `021-${Math.floor(Math.random() * 9000 + 1000)}-${Math.floor(Math.random() * 9000 + 1000)}`,
            address: `上海市${dept.slice(0, 2)}路${Math.floor(Math.random() * 100) + 1}号`,
            birthday: new Date(1980 + Math.floor(Math.random() * 40), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1).toISOString().split('T')[0],
            idcard: `31010119${String(1980 + Math.floor(Math.random() * 40)).slice(2)}${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}${Math.floor(Math.random() * 1000) + 1000}X`,
            departIds: [Math.floor(Math.random() * 5) + 1, Math.floor(Math.random() * 5) + 1].join(','),
            departNames: dept,
            userAgentId: i + 100,
            userAgentName: `代理人${i}`,
            userAgentStartTime: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toISOString(),
            userAgentEndTime: new Date(Date.now() + Math.floor(Math.random() * 10000000000)).toISOString(),
            userAgentStatus: '1',
            thirdId: `third_${i}`,
            thirdType: 'wechat',
            regEmail: `reg_user${i}@example.com`,
            regPhone: `139${String(i).padStart(8, '0')}`,
            regUserType: '1',
            regUserStatus: '1',
            regUserSource: '1',
            regUserRemark: `注册备注 ${i}`,
            regUserAgent: `注册代理人${i}`,
            regUserAgentPhone: `137${String(i).padStart(8, '0')}`,
            regUserAgentEmail: `agent${i}@example.com`,
            regUserAgentAddress: `代理地址 ${i}`,
            regUserAgentRemark: `代理备注 ${i}`,
            regUserAgentStatus: '1',
            regUserAgentCreateTime: new Date(Date.now() - Math.floor(Math.random() * 5000000000)).toISOString(),
            regUserAgentUpdateTime: new Date(Date.now() - Math.floor(Math.random() * 2500000000)).toISOString(),
        });
    }

    return data;
};

let mockRoles = generateMockRoleData();
let mockUsers = generateMockUserData();

// 模拟角色-用户关联关系
let mockRoleUserAssociations: { roleId: string; userId: string }[] = [];
// 为每个角色随机分配一些用户
mockRoles.forEach(role => {
    const userCount = Math.floor(Math.random() * 20) + 1; // 每个角色关联 1-20 个用户
    const shuffledUsers = [...mockUsers].sort(() => 0.5 - Math.random());
    shuffledUsers.slice(0, userCount).forEach(user => {
        mockRoleUserAssociations.push({ roleId: role.id, userId: user.id.toString() });
    });
});

export default {
    // 获取角色列表 (复用)
    'GET /sys/role/list': async (req: any, res: any) => {
        await waitTime(500);

        const { current = 1, pageSize = 10, roleName, roleCode } = req.query;

        let filteredRoles = [...mockRoles];

        if (roleName) {
            filteredRoles = filteredRoles.filter(r => r.roleName.includes(roleName));
        }
        if (roleCode) {
            filteredRoles = filteredRoles.filter(r => r.roleCode.includes(roleCode));
        }

        const start = (parseInt(current) - 1) * parseInt(pageSize);
        const end = start + parseInt(pageSize);
        const paginatedData = filteredRoles.slice(start, end);

        res.json({
            success: true,
            message: '获取成功',
            result: {
                records: paginatedData,
                total: filteredRoles.length,
            },
        });
    },

    // 删除单个角色 (复用)
    'DELETE /sys/role/delete': async (req: any, res: any) => {
        await waitTime(300);
        const { id } = req.query;

        const index = mockRoles.findIndex(r => r.id === id);
        if (index > -1) {
            mockRoles.splice(index, 1);
            // 删除关联的用户关系
            mockRoleUserAssociations = mockRoleUserAssociations.filter(assoc => assoc.roleId !== id);
            res.json({
                success: true,
                message: '删除成功',
            });
        } else {
            res.status(404).json({
                success: false,
                message: '未找到角色',
            });
        }
    },

    // 获取指定角色下的用户列表
    'GET /sys/user/queryUserListByRelation': async (req: any, res: any) => {
        await waitTime(500);

        const { current = 1, pageSize = 10, roleId } = req.query; // 假设后端通过 roleId 筛选

        if (!roleId) {
            res.json({
                data: [],
                success: true,
                total: 0,
            });
            return;
        }

        let filteredUsers = mockUsers.filter(user =>
            mockRoleUserAssociations.some(assoc => assoc.roleId === roleId && assoc.userId === user.id.toString())
        );

        // 应用其他查询条件 (如果需要)
        // const { account, realname, ... } = req.query;
        // if (account) { ... }

        const start = (parseInt(current) - 1) * parseInt(pageSize);
        const end = start + parseInt(pageSize);
        const paginatedData = filteredUsers.slice(start, end);

        res.json({
            success: true,
            message: '获取成功',
            result: {
                records: paginatedData,
                total: filteredUsers.length,
            },
        });
    },

    // 为用户添加角色
    'POST /sys/user/addSysUserRole': async (req: any, res: any) => {
        await waitTime(300);
        const { userId, roleId } = req.body; // 假设后端接收 userId 和 roleId

        // 检查关联是否已存在
        const exists = mockRoleUserAssociations.some(assoc => assoc.userId === userId && assoc.roleId === roleId);
        if (exists) {
            res.status(400).json({
                success: false,
                message: '用户角色关联已存在',
            });
            return;
        }

        mockRoleUserAssociations.push({ userId, roleId });
        res.json({
            success: true,
            message: '添加成功',
        });
    },

    // 删除用户角色关联 (单个)
    'DELETE /sys/user/deleteUserRole': async (req: any, res: any) => {
        await waitTime(300);
        const { userId, roleId } = req.query; // 假设后端通过 query 参数接收

        const index = mockRoleUserAssociations.findIndex(assoc => assoc.userId === userId && assoc.roleId === roleId);
        if (index > -1) {
            mockRoleUserAssociations.splice(index, 1);
            res.json({
                success: true,
                message: '删除成功',
            });
        } else {
            res.status(404).json({
                success: false,
                message: '未找到用户角色关联',
            });
        }
    },

    // 批量删除用户角色关联
    'DELETE /sys/user/deleteUserRoleBatch': async (req: any, res: any) => {
        await waitTime(500);
        const { userIds, roleId } = req.query; // 假设后端接收 userIds 数组和 roleId
        const userIdList = (userIds as string).split(',');

        const initialLength = mockRoleUserAssociations.length;
        userIdList.forEach((userId: string) => {
            const index = mockRoleUserAssociations.findIndex(assoc => assoc.userId === userId && assoc.roleId === roleId);
            if (index > -1) {
                mockRoleUserAssociations.splice(index, 1);
            }
        });
        const deletedCount = initialLength - mockRoleUserAssociations.length;

        res.json({
            success: deletedCount > 0,
            message: `成功删除 ${deletedCount} 条记录`,
        });
    },

    // 获取所有用户 (用于选择用户)
    'GET /sys/user/queryall': async (req: any, res: any) => {
        await waitTime(300);
        // 可能需要过滤掉已经分配给当前角色的用户
        const { roleId } = req.query;
        let availableUsers = mockUsers;
        if (roleId) {
            availableUsers = mockUsers.filter(user =>
                !mockRoleUserAssociations.some(assoc => assoc.roleId === roleId && assoc.userId === user.id.toString())
            );
        }
        res.json({
            success: true,
            message: '获取成功',
            result: availableUsers,
        });
    },
};